import request from '@/utils/request'
import store from '@/store'
import {removeToken, setToken} from '@/utils/token'
import router from '../router'

function loginByUsername (username, password) {
  const data = {
    username,
    password
  }
  return request({
    url: '/login',
    method: 'post',
    data
  });
}

export function login (username, password) {
  return new Promise((resolve, reject) => {
    loginByUsername(username, password).then(() => {
      setToken(true);
      // store.dispatch('delAllViews');
      router.push('/');
      resolve();
    }).catch((err) => {
      reject(err);
    });
  })
}

function logout_ () {
  return request({
    url: '/logout',
    method: 'get'
  })
}

export function logout () {
  return new Promise((resolve, reject) => {
    logout_().then(() => {
      removeToken();
      store.dispatch('logoutClear');
      // store.dispatch('setMenu', []); // 清空菜单以便登录后重新获取(相当于清空vuex)
      store.dispatch('delAllViews'); // 删除保存的view tags
      router.push('/login');
    });
  })
}

export function getLoginUserInfo () {
  return request({
    url: '/userinfo',
    method: 'get'
  })
}

export function getDict () {
  return request({
    url: '/dict/all',
    method: 'get'
  });
}

export function getMenus () {
  return request({
    url: '/authinfo',
    method: 'get'
  });
}
